//
//  Bundle+AD.swift
//  ADKit
//
//  Created by Adoma on 2020/10/22.
//

import SwiftyJSON

public extension Bundle {
    
    var info: JSON { JSON(infoDictionary ?? [:]) }
        
    var name: String {
        info["CFBundleName"].stringValue
    }
    
    var version: String {
        info["CFBundleShortVersionString"].stringValue
    }
    
    var build: String {
        info["CFBundleVersion"].stringValue
    }
    
    var identifier: String {
        bundleIdentifier ?? ""
    }
    
    /// by ADKit
    static func `for`(module: String? = nil, name: String? = nil, cls: AnyClass? = nil) -> Bundle {
       
        var bundle = main
        
        if let module = module,
           let frameworkUrl = bundle.url(forResource: "Frameworks", withExtension: nil)?.appendingPathComponent(module).appendingPathExtension("framework"),
           let moduleBundle = Bundle.init(url: frameworkUrl) {
            bundle = moduleBundle
        }
        
        if let name = name,
           let bundleUrl = bundle.url(forResource: name, withExtension: "bundle"),
           let sourceBundle = Bundle.init(url: bundleUrl) {
            bundle = sourceBundle
        }
        
        if let cls = cls {
            bundle = Bundle.init(for: cls)
        }
        
        return bundle
    }
}
